<?php

namespace App\Http\Controllers\api;

use App\Constant\Enum;
use App\Models\User;
use App\Services\Login\OAuth;
use App\Services\Wallet\UserWalletService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use function Psy\debug;

class OAuthController extends BaseController
{
    public function login(Request $request, OAuth $oauth)
    {
        $attributes = $request->validate([
            'driver' => 'required|in:apple,wechat,phone',
            'code' => 'required_if:driver,wechat|required_if:driver,phone',
            'id_token' => 'required_if:driver,apple',
            'name' => 'nullable',
            "mobile" => 'required_if:driver,phone',
            'cid' => 'nullable',
            'pid' => 'nullable',
        ]);
        try {
            Log::channel('oauth')->info('OAuth Login参数:' . json_encode($attributes));
            $token = $oauth->handle($attributes);
            return $this->respondWithToken($token);
        } catch (\Exception $exception) {
            Log::error('OAuth Failed Login:' . $exception->getMessage());
            Log::error($exception);
            return $this->error("授权登录失败，请重试");
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('jwt')->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    protected function respondWithToken($token)
    {
        $user = auth('jwt')->setToken($token)->user();
        if ($user->getAttribute('status') != Enum::STATUS_ENABLED) {
            return $this->error('用户封禁中，请联系管理员！');
        }

        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('jwt')->factory()->getTTL() * 60,
            'user' => $this->getUserInfo($user),
        ]);
    }

    private function getUserInfo(User $user)
    {
        $parent = $user->parent()->first();
        $user->parent_uuid = $parent->uuid ?? '';

        $user->withdrawable_coins = UserWalletService::getWithdrawableCoins($user);
        $user->today_coins = UserWalletService::getTodayCoins($user);

        return $user;
    }
}
